<?php if (! defined ( 'BASEPATH' )) exit ( 'No direct script access allowed' );
/**
* tai khoan he thong
*/
Class Admin extends Admin_Controller {

	function __construct() {
		parent::Admin_Controller ();
		$this->load->library ( 'session' );
		$this->load->library ( 'user_lib' );
		$this->load->helper(array('string', 'security'));
		$this->load->model ( 'users_m' );
		$this->load->model ( 'roles_m' );
		$this->load->helper ( 'user' );
		$this->lang->load ( 'user' );
		$this->data->roles = toKeyNamePairs('name', 'name', $this->roles_m->getRoles ());
	}

	// Admin: List all User
	function index() {
		$filter = array ();

		if ($this->input->post ( 'add' )) {
			redirect ( 'admin/users/create' );
		} else if ($this->input->post('delete')) {
			$ids = $this->input->post ( 'action_to' );
			if (! empty ( $ids )) {
				$deleted = 0;
				$to_delete = 0;
				foreach ( $ids as $id ) {
					// Make sure the admin is not trying to delete themself
					if ($this->user_lib->user_data->id == $id) {
						$this->session->set_flashdata( 'notice', $this->lang->line ( 'user_delete_self_error' ) );
						continue;
					}
					if ($this->users_m->deleteUser ( $id )) {
						$deleted ++;
					}
					$to_delete ++;
				}
				if ($to_delete > 0) {
					$this->session->set_flashdata( 'success', sprintf ( $this->lang->line ( 'user_mass_delete_success' ), $deleted, $to_delete ) );
				}
			} // The array of id's to delete is empty
			else
				$this->session->set_flashdata( 'error', $this->lang->line ( 'user_mass_delete_error' ) );
			redirect ( 'admin/users/index' );
		} else if ($this->input->post('edit')) {
			$ids = $this->input->post ( 'action_to' );
			if (! empty ( $ids ) && count($ids) == 1) {
				redirect ('admin/users/edit/'.$ids[0]);
			} else {
				$this->session->set_flashmessage( 'error', $this->lang->line ( 'user_mass_edit_error' ) );
			}
		}

		if(!empty($_POST)) {
			$filter = $_POST;
		} else {
			$filter['keyword'] = '';
			$filter['search_on'] = 'name';
			$filter['role'] = '';
			$filter['is_active'] = '-1';
		}
		if ($filter['search_on'] == 'name'){
			$filter['name'] = trim($filter['keyword']);
		}else if ($filter['search_on'] == 'email'){
			$filter['email'] = trim($filter['keyword']);
		}

		// Using this data, get the relevant results
		$filter['order'] = 'id desc';
		$this->data->users = $this->users_m->getUsers ( $filter );

		// Create pagination links
		$filter['count'] = true;
		$total_rows = $this->users_m->getUsers ( $filter );
		//$this->data->pagination = create_pagination ( 'admin/banks/index', $total_rows, $filter ['limit'], $filter ['start'] );
		// How many inactive users are on the site?
		//$this->data->inactive_user_count = $this->users_m->countUsers ( array ('active' => 0 ) );
		$this->data->total = $total_rows;
		$this->data->filter = $filter;
		$this->data->roles = $this->roles_m->getRoles();
		//Toolbar
		$this->data->toolbar = createToolbar ( array (array ('command' => 'add' ), array ('command' => 'edit' ), array ('command' => 'delete' ) ), array ('label' => 'Quản lý tài khoản', 'attribute' => 'class = "acc_permission toolbar_title"' ) );
		$this->layout->create ( 'admin/index', $this->data );
	}

	// Admin: Different form actions
	function action() {
		switch ($this->input->post ( 'btnAction' )) {
			case 'activate' :
				$this->activate ();
				break;
			case 'delete' :
				$this->delete ();
				break;
			default :
				redirect ( 'admin/users/index' );
				break;
		}
	}

	// Admin: create a new User
	function create() {
		$this->load->library ( 'validation' );
		$filter = array(
 			'email' => '',
 			'password' => '',
 			'role' => '',
 			'name' => '',
 			'is_active' => ''
 		);
		$fields = array(
			'name' => 'Tên',
			'email' => 'Email',
			'password' => 'Mật khẩu'
			,'confirm_password' => 'Mật khẩu xác nhận'
		);
		$this->rules = array(
			'name' => 'required',
			'email'	=> 'required|valid_email',
			'password' => 'required|min_length[6]',
			'confirm_password' => 'required|min_length[6]|matches[password]'
		);
		// Adding a user, we must have a password

		$this->validation->set_rules ( $this->rules);
		$this->validation->set_fields ($fields);

		$email = $this->input->post ( 'email' );
		$password = $this->input->post ( 'password' );

		if ($this->input->post('Cancel')){
			redirect('admin/users/index');
		}
		if($this->input->post('Save')){
			foreach($filter as $k=>$v){
					$filter[$k] = $this->input->post($k);
			}
			if (!$this->validation->run ()) {
				// Return the validation error message or user_lib error
				$this->session->set_flashmessage($this->validation->error_string);
			} else {
				$chk_email = $this->users_m->get_where(array('email'=>$email));
				if($chk_email){
					$this->session->set_flashmessage('error',"Tài khoản đã tồn tại");
				} else {
					$salt = random_string('alnum', 5);
					$filter['salt'] = $salt;
					$password = dohash($password . $salt);
					$filter['password'] = $password;
					$this->users_m->insert($filter);
					$this->session->flashdata('success',"Tạo tài khoản thành công");
					redirect('admin/users/index');
				}
			}
		}

		$this->data->filter = $filter;
		$this->data->toolbar = createToolbar ( array (array ('command' => 'Save' ), array ('command' => 'Cancel', 'attribute'=>'class="btn_admin"' )), array ('label' => $this->lang->line ( 'user_add_title' ), 'attribute' => 'class = "acc_per toolbar_title"' ) );
		$this->layout->create ( 'admin/form', $this->data );
	}

	// Admin: Edit a User
	function edit($id = 0) {
		$this->load->library ( 'validation' );

		// Shouldnt need to have done this, but if password exists make confirm_password required
		$fields = array(
			'name' => 'Tên',
			'email' => 'Email',
			'password' => 'Mật khẩu'
			,'confirm_password' => 'Mật khẩu xác nhận'
		);
		$this->rules = array(
			'name' => 'required',
			'email'	=> 'required|valid_email',
		);
		if($this->input->post('password') || $this->input->post('confirm_password')){
			$this->rules['password'] =	'required|min_length[6]';
			$this->rules['confirm_password'] = 'required|min_length[6]|matches[password]';
		}
		$this->validation->set_rules ( $this->rules );
		$this->validation->set_fields ();
		$this->data->member = $this->users_m->getUser ( array ('id' => $id ) );
		if (! $this->data->member) {
			$this->session->set_flashdata ( 'error', $this->lang->line ( 'user_edit_user_not_found_error' ) );
			redirect ( 'admin/users' );
		}

		if ($this->input->post('cancel')){
			redirect('admin/users/index');
		}

		if ($this->validation->run ()) {
			//$update_data ['first_name'] = $this->input->post ( 'first_name' );
			$update_data ['name'] = $this->input->post ( 'name' );
			$update_data ['email'] = $this->input->post ( 'email' );
			$update_data ['is_active'] = $this->input->post ( 'is_active' );
			// Only worry about role if there is one, it wont show to people who shouldnt see it
			if ($this->input->post ( 'role' ))
				$update_data ['role'] = $this->input->post ( 'role' );

			// Password provided, hash it for storage
			if ($this->input->post ( 'password' ) && $this->input->post ( 'confirm_password' )) {
				$this->load->helper ( 'security' );
				$update_data ['password'] = dohash ( $this->input->post ( 'password' ) . $this->data->member->salt );
			}

			if ($this->users_m->updateUser ( $id, $update_data )) {
				$this->session->set_flashdata ( 'success', $this->lang->line ( 'user_edit_success' ) );
			} else {
				$this->session->set_flashdata ( 'error', $this->lang->line ( 'user_edit_error' ) );
			}
			redirect ( 'admin/users' );
		} else {
			$this->data->error_string = $this->validation->error_string;
		}

		$this->data->toolbar = createToolbar ( array (array ('command' => 'save' ), array ('command' => 'cancel', 'attribute'=>'class="btn_admin"' )), array ('label' => sprintf($this->lang->line ( 'user_edit_title' ), $this->data->member->name), 'attribute' => 'class = "acc_per toolbar_title"' ) );
		$this->layout->create ( 'admin/form_edit_user', $this->data );
	}

}
?>